import { Table } from 'antd'
import { TablePaginationConfig } from 'antd/es/table'
import React, { useState } from 'react'
import { ResizeCallbackData } from 'react-resizable'
import ResizableTitle from '../ResizableTitle'

type ResizableTableProps = {
  dataSource: object[]
  columnsList: object[]
  pagination?: TablePaginationConfig | false
  scroll?: object
  rowKey?: string
  onChange?: any
  showSorterTooltip?: any
  expandable?: any
  rowSelection?: any
}

const ResizableTable = (props: ResizableTableProps) => {
  const {
    dataSource,
    columnsList,
    pagination,
    scroll,
    rowKey = 'id',
    onChange,
    showSorterTooltip,
    expandable,
    rowSelection
  } = props
  console.log('🚀 ~ ResizableTable ~ columnsList:', columnsList)

  const [columns, setColumns] = useState(columnsList)
  const handleResize =
    (index: number) =>
    (_: React.SyntheticEvent<Element>, { size }: ResizeCallbackData) => {
      const newColumns = [...columns]
      newColumns[index] = {
        ...newColumns[index],
        width: size.width
      }
      setColumns(newColumns)
    }

  const mergeColumns = columns.map((col, index) => ({
    ...col,
    onHeaderCell: (column: any) => ({
      width: column.width,
      onResize: handleResize(index) as React.ReactEventHandler<any>
    })
  }))
  return (
    <Table
      bordered
      columns={mergeColumns}
      rowKey={rowKey}
      components={{
        header: {
          cell: ResizableTitle
        }
      }}
      scroll={scroll}
      pagination={pagination}
      dataSource={dataSource}
      onChange={onChange}
      showSorterTooltip={{ ...showSorterTooltip }}
      expandable={{ ...expandable }}
      rowSelection={{ ...rowSelection }}
    />
  )
}

export default ResizableTable
